using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.DataControls
{
    [System.ComponentModel.Designer(typeof(TemplateControlDataSourceDesigner))]
    [System.Web.UI.ToolboxData("<{0}:TemplateControlDataSource runat=server/>")]
    public class TemplateControlDataSource : GenericDataSource<Bll.TemplateControl>
    {
        public enum Fields
        {
            Id,
            TemplateId,
            Name,
            TypeId,
            ConcurencyId
        }

        protected override Acms.Bll.TemplateControl PopulateData(UpdateAction action, System.Collections.IDictionary keys, System.Collections.IDictionary values, System.Collections.IDictionary oldValues)
        {
            Bll.TemplateControl tmp = null;
            byte[] concurencyId = null;

            if (action == UpdateAction.Insert)
            {
                tmp = Bll.TemplateControl.CreateInstance();
            }
            else
            {
                int id = GetValue<int>(Fields.Id, keys);
                concurencyId = GetValue<byte[]>(Fields.ConcurencyId, keys);
                tmp = Bll.TemplateControl.GetById(id);
            }

            if (tmp != null)
            {
                if (RequiresUpdate<int>(Fields.TemplateId, values, oldValues))
                {
                    tmp.TemplateId = GetValue<int>(Fields.TemplateId, values);
                }

                if (RequiresUpdate<string>(Fields.Name, values, oldValues))
                {
                    tmp.Name = GetValue<string>(Fields.Name, values);
                }

                if (RequiresUpdate<int>(Fields.TypeId, values, oldValues))
                {
                    tmp.TypeId = GetValue<int>(Fields.TypeId, values);
                }
            }
            return tmp;
        }

        protected override int SaveChanges(Acms.Bll.TemplateControl item)
        {
            item.Update();
            return 1;
        }

        protected override void AddInsertedKey(Acms.Bll.TemplateControl item, System.Collections.IDictionary values)
        {
            values[Fields.Id.ToString()] = item.Id;
        }

        protected override int Delete(Acms.Bll.TemplateControl item)
        {
            item.Delete();
            return 1;
        }
    }

    public class TemplateControlDataSourceDesigner : GenericDataSourceDesigner<Bll.TemplateControl>
    {
        protected override Acms.Bll.TemplateControl GetDesignTimeItem(int index)
        {
            string[] names = new string[]{"Introduction", "Main Image", "Body 1", "Quote", "Instructions"};
            Random rnd = new Random(index);
            Bll.TemplateControl tmp = Bll.TemplateControl.CreateInstance();
            tmp.Name = names[rnd.Next(0, names.Length)];
            tmp.TemplateId = 1;
            tmp.TypeId = 1;
            return tmp;
        }
    }
}
